package com.bzkj.common.utils;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 融合系统Token工具类
 *
 * @author chj
 */
@Component
public class FusionTokenUtils {

    @Value("${msfx-fusion.baseUrl}")
    private String baseUrl;

    @Value("${msfx-fusion.username}")
    private String username;

    @Value("${msfx-fusion.password}")
    private String password;

    private static String BASE_URL;
    private static String USERNAME;
    private static String PASSWORD;

    @PostConstruct
    public void init() {
        BASE_URL = baseUrl;
        USERNAME = username;
        PASSWORD = password;
    }

    public static String getToken() {
        HttpURLConnection conn = null;
        try {
            // 1. 定义目标 URL
            URL url = new URL(BASE_URL + "/WMS/login");
            conn = (HttpURLConnection) url.openConnection();

            // 2. 设置请求方法为 POST
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json"); // 设置请求头
            conn.setDoOutput(true); // 允许输出流

            // 3. 构建请求体（例如 JSON）
            String requestBody = "{" +
                    "    \"username\":\"" + USERNAME + "\"," +
                    "    \"password\":\"" + PASSWORD + "\"" +
                    "}";

            // 4. 发送请求体
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 5. 读取响应
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                JSONObject jsonObject = JSONObject.parseObject(response.toString());
                if (jsonObject != null && "200".equals(jsonObject.get("code").toString())) {
                    return jsonObject.getString("token");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return "";
    }
}